import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormControl, UntypedFormGroup } from '@angular/forms';
import { NzTableQueryParams } from 'ng-zorro-antd/table';
import { BehaviorSubject } from 'rxjs';
import { Consts } from 'src/app/consts/consts';
import { ClientMenuQueryParam } from 'src/app/models/param/client-menu-query.param';
import { ClientMenuDto } from 'src/app/models/sys/client-menu.dto';
import { ApiService } from 'src/app/services/api.service';

@Component({
  selector: 'app-client-permission',
  templateUrl: './client-permission.component.html',
  styleUrls: ['./client-permission.component.less']
})
export class ClientPermissionComponent implements OnInit {
  @Input() clientIdSubject = new BehaviorSubject<string>('');
  clientId?: string;

  searchForm!: UntypedFormGroup;

  clientMenus: ClientMenuDto[] = [];
  pageIndex = 1;
  pageSize = 10;
  total = 0;

  constructor(private _api: ApiService,
    private _fb: FormBuilder) {}

  ngOnInit(): void {
    this.createSearchForm();
    this.clientIdSubject.subscribe((value) => {
      this.clientId = value;
      this.onSearch();
    });
  }

  createSearchForm() {
    this.searchForm = this._fb.group({
      menuName: new FormControl(''),
      perms: new FormControl('')
    });
  }

  onReset() {}

  onSearch() {
    const param = new ClientMenuQueryParam();
    param.id = this.clientId;
    param.pageNum = this.pageIndex;
    param.pageSize = this.pageSize;
    param.menuName = this.searchForm.get('menuName')?.value;
    param.perms = this.searchForm.get('perms')?.value;

    this._api.getClientMenu(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK && resp.data) {
        this.clientMenus = resp.data;
        this.total = resp.total;
      }
    });
  }

  onPageParamChange(params: NzTableQueryParams) {
    this.pageIndex = params.pageIndex;
    this.pageSize = params.pageSize;
    this.onSearch();
  }
}
